package com.iot.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot.manage.pojo.Gateway;
import com.iot.manage.pojo.SysCode;
import com.iot.manage.result.Code;
import com.iot.manage.result.Result;
import com.iot.manage.service.GatewayService;
import com.iot.manage.service.TokenService;
import com.iot.manage.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 网关管理控制层
 *
 * @author zhuzhi
 */
@RestController
@RequestMapping("/api/private/v1")
public class GatewayController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private GatewayService gatewayService;

    /**
     * 查询网关信息列表
     *
     * @param token
     * @param query 模糊查询关键字
     * @param pagenum 当前页
     * @param pagesize 每页条数
     * @return
     */
    @GetMapping("/findGatewayList")
    public Result findGatewayList(
            @RequestHeader("token") String token,
            @RequestParam("query") String query,
            @RequestParam("pagenum") int pagenum,
            @RequestParam("pagesize") int pagesize) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Gateway> gatewayList;
        int gatewayTotal;
        try{
            gatewayList = gatewayService.findGatewayList(query,pagenum,pagesize);
            gatewayTotal = gatewayService.countGatewayList(query);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total",gatewayTotal);
        map.put("pagenum",pagenum);
        map.put("gatewayList",gatewayList);
        return result.build(map, Code.S200);
    }

    /**
     * 查询父网关下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findGatewayParentCodeList")
    public Result findGatewayParentCodeList(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<SysCode> gatewayParentCodeList;
        try{
            gatewayParentCodeList = gatewayService.findGatewayParentCodeList();
//            SysCode sysCode = new SysCode();
//            sysCode.setCodeValue(" ");
//            sysCode.setCodeName("无");
//            gatewayParentCodeList.add(0,sysCode);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(gatewayParentCodeList, Code.S200);
    }

    /**
     * 查询网关类型下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findGatewayTypeList")
    public Result findGatewayTypeList(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<SysCode> gatewayTypeList;
        try{
            gatewayTypeList = gatewayService.findGatewayTypeList();
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(gatewayTypeList, Code.S200);
    }

    /**
     * 新增网关信息
     *
     * @param token
     * @param params 网关信息参数
     * @return
     */
    @PostMapping("/addGatewayInfo")
    public Result addGatewayInfo(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if(null != findGatewayInfoByIdOrCode(token,params.getString("gatewayCode")).getData()){
                return result.build(null, Code.D411);
            }
            params.put("gatewayId", UUID.randomUUID().toString().replace("-", ""));
            params.put("gatewayArg", StringUtils.replaceBlank(params.get("gatewayArg").toString()));
            gatewayService.addGatewayInfo(params);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 根据网关ID或网关标识查询网关信息
     *
     * @param token
     * @param params 网关ID或网关标识
     * @return
     */
    @GetMapping("/findGatewayInfoById/{params}")
    public Result findGatewayInfoByIdOrCode(
            @RequestHeader("token") String token,
            @PathVariable("params") String params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        Gateway gateway;
        try{
            gateway = gatewayService.findGatewayInfoByIdOrCode(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(gateway, Code.S200);
    }

    /**
     * 修改网关信息
     *
     * @param token
     * @param params 网关信息参数
     * @return
     */
    @PutMapping("/updateGatewayInfo/{oldGatewayCode}")
    public Result updateGatewayInfo(
            @RequestHeader("token") String token,
            @PathVariable("oldGatewayCode") String oldGatewayCode,
            @RequestBody JSONObject params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if (!(oldGatewayCode.equals(params.get("gatewayCode")))){
                if(null != findGatewayInfoByIdOrCode(token,params.getString("gatewayCode")).getData()){
                    return result.build(null, Code.D411);
                }
            }
            params.put("gatewayArg", StringUtils.replaceBlank(params.get("gatewayArg").toString()));
            gatewayService.updateGatewayInfo(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     *删除网关信息
     *
     * @param token
     * @param gatewayId 网关ID
     * @return
     */
    @DeleteMapping("/removeGatewayInfo/{gatewayId}")
    public Result removeGatewayInfo(
            @RequestHeader("token") String token,
            @PathVariable("gatewayId") String gatewayId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            int total = gatewayService.countGatewayParentById(gatewayId);
            if (total > 0){
                return result.build(null,Code.WARM);
            }
            gatewayService.removeGatewayInfo(gatewayId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     *删除子网关不为空的网关信息
     *
     * @param token
     * @param gatewayId 网关ID
     * @return
     */
    @DeleteMapping("/removeGatewayInfoParent/{gatewayId}")
    public Result removeGatewayInfoParent(
            @RequestHeader("token") String token,
            @PathVariable("gatewayId") String gatewayId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            gatewayService.updateGatewayParent(gatewayId);
            gatewayService.removeGatewayInfo(gatewayId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }
}
